﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FrameDisplay.Services;
using System.IO;
using System.ServiceModel.Web;

namespace FrameDisplayServer.Services.WebInterface
{
    class WebInterfaceService : IWebInterfaceService
    {
        private Stream GetInvalidAccessCodeStream()
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/html; charset=utf-8";
            StringBuilder html = new StringBuilder();
            html.Append("<html>");
            html.Append("<head>");
            html.Append("</head>");
            html.Append("<body>");
            html.Append("Invalid access code.");
            html.Append("</body>");
            html.Append("</html>");
            MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(html.ToString()));
            return memStream;
        }

        public Stream GetDataFile(string file)
        {      
            if (file.IndexOf("..") > 0)
            {
                throw new Exception("Invalid file specified.");
            }

            // switch url separator for local file separator.
            file = file.Replace('/', '\\');

            string extension = Path.GetExtension(file.ToLower());

            if (extension == "js") {
                WebOperationContext.Current.OutgoingResponse.ContentType = "text/javascript; charset=utf-8";
            }            

            // Find file in Services/WebInterface/data            
            string codeBase = System.Reflection.Assembly.GetEntryAssembly().CodeBase;
            Uri codeBaseUri = new Uri(codeBase);
            string codeBaseDirectory = Path.GetDirectoryName(codeBaseUri.LocalPath);

            string dataPath =  @"\Services\WebInterface\data\";
            if (!codeBaseDirectory.EndsWith(@"\"))
                dataPath = codeBaseDirectory + @"\" + dataPath;            
            else
                dataPath = codeBaseDirectory + dataPath;

            string filePath = dataPath + file;

            if (File.Exists(filePath))
            {
                return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            else
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
                return null;
            }
        }

        public Stream MouseWatch(string accessCode)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/html; charset=utf-8";
           
            if (accessCode != AppCentral.SettingsManager.AccessCode)
            {
                return this.GetInvalidAccessCodeStream();
            }

            string baseUrl = null;

            string host = WebOperationContext.Current.IncomingRequest.Headers["Host"];
            if (!String.IsNullOrEmpty(host))
            {
                // TODO: We might eventually need to support https here.

                // This is preferred since client might have originally contacted us from an IP address or other forwarded address.
                baseUrl = "http://" + host + "/";
            }
            else
            {
                baseUrl = AppCentral.ServiceManager.BaseUrl;
            }

            StringBuilder html = new StringBuilder();

            html.Append("<html>");
            html.Append("<head>");

            html.Append("<meta name='viewport' content='width=device-width, user-scalable=no' />");

            html.Append("<script type='text/javascript' src='data/yui-all-combined.js'></script>");
            html.Append("<script type='text/javascript' src='data/WebInterface.js?" + Environment.TickCount + "'></script>");
            html.Append("<script type='text/javascript' src='data/js/FrameDisplay.Services.js?" + Environment.TickCount + "'></script>");

            html.Append("</head>");
            html.Append("<body style='margin: 0px; padding: 0px' onkeypress='return handleKey(event)'>");

            html.Append(@"
<script type='text/javascript'><!--
FrameDisplay.baseUrl = '" + baseUrl + @"';
FrameDisplay.accessCode = '" + accessCode + @"';
var mouseWatchPad = new FrameDisplay.MouseWatchPad();
mouseWatchPad.init();
--></script>
");          

            html.Append("<input id='inputElement' type='text' size='1' style='display: none' />");                      

            html.Append("</body>");
            html.Append("</html>");

            MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(html.ToString()));
            return memStream;
        }

    }
}
